const express=require('express')
const app=express()
const md5=require("md5")
const bodyParser=require('body-parser')
const db=require('./module/db')
const {json,encode,decode}=require("./fools.js")
const fs=require("fs")
const mongodb=require("mongodb")
const path=require("path")
const {upPic}=require("./module/upPic")
const formidable=require('formidable')
app.use(bodyParser.json())
app.use(express.static(__dirname+"/upload"))
app.post("/login",function (req,res) {
    const {adminName,passWord}=req.body
    db.findOne("adminInfo",{
        adminName,
        passWord:md5(passWord+"*^&%**(%$")
    }).then(async userInfo=>{
       if(userInfo){
           await db.insertOne("adminLog",{
               adminName,
               loginTime:Date.now()
           })
           res.json({
               ok:1,
               msg:"成功",
               adminName,
               token:encode(adminName)
           })
        }else{
           json(res,-1,"账号或密码错误")
        }
    })
})



app.all("*",function (req,res,next) {
    const {ok,info,msg}= decode(req.headers.authorization)
    //判断是否解析成功
    if(ok===1){
        next()
    }else{
        json(res,-2,msg)
    }
})
app.get("/adminLog",async function (req,res) {
    let pageIndex=(req.query.pageIndex || 1)/1  //当前页
    let count=await db.count('adminLog')   //总条数
    let limit=5;  //一页显示
    let pageSum=Math.ceil(count/limit)   //总页数
    if(pageSum<1) pageSum=1
    if(pageIndex>pageSum)pageIndex=pageSum
    if(pageIndex<1) pageIndex=1

        db.find("adminLog",{
            sortObj:{
                loginTime: -1
            },
            limit,
            skip:(pageIndex-1)*limit

        }).then(adminLog=>{
            setTimeout(()=>{
                res.json({
                    ok:1,
                    adminLog,
                    pageIndex,
                    pageSum
                })
            },500)
        })
})
app.get("/adminList",async function (req,res) {
    let pageIndex=(req.query.pageIndex || 1)/1  //当前页
    let count=await db.count('adminInfo')   //总条数
    let limit=5;  //一页显示
    let pageSum=Math.ceil(count/limit)   //总页数
    if(pageSum<1) pageSum=1
    if(pageIndex>pageSum)pageIndex=pageSum
    if(pageIndex<1) pageIndex=1

    db.find("adminInfo",{
        sortObj:{
            loginTime: -1
        },
        limit,
        skip:(pageIndex-1)*limit

    }).then(adminInfo=>{
        setTimeout(()=>{
            res.json({
                ok:1,
                adminInfo,
                pageIndex,
                pageSum
            })
        },500)
    })
})

app.get("/shopTypeList",async function (req,res) {
    let pageIndex=(req.query.pageIndex || 1)/1  //当前页
    const whereObj={};
    let shopTypeName=req.query.shopTypeName || ""
    if(shopTypeName.length>0){
        whereObj.shopTypeName=new RegExp(shopTypeName)
    }
    let count=await db.count('shopTypeList')   //总条数
    let limit=5;  //一页显示
    let pageSum=Math.ceil(count/limit)   //总页数
    if(pageSum<1) pageSum=1
    if(pageIndex>pageSum)pageIndex=pageSum
    if(pageIndex<1) pageIndex=1

    db.find("shopTypeList",{
        sortObj:{
            createTime: -1
        },
        whereObj,
        limit,
        skip:(pageIndex-1)*limit

    }).then(shopTypeList=>{
        setTimeout(()=>{
            res.json({
                ok:1,
                shopTypeList,
                pageIndex,
                pageSum
            })
        },500)
    })
})

app.get("/allShopTypeList",async function (req,res) {
    db.find("shopTypeList",{
        sortObj:{
            createTime:-1
        },
    }).then(shopTypeList=>{
        res.json({
            ok:1,
            shopTypeList
        })
    })
})

app.delete("/adminLog/:id",function (req,res) {
    const id=req.params.id
    db.deleteOneById("adminLog",id)
        .then(()=>{
            json(res,1,"删除成功")
        }).catch(()=>{
            json(res,-1,"网络异常删除错误")
    })
})
app.delete("/shopTypeList/:id",function (req,res) {
    const id=req.params.id
    db.deleteOneById("shopTypeList",id)
        .then(()=>{
            json(res,1,"删除成功")
        }).catch(()=>{
        json(res,-1,"网络异常删除错误")
    })
})
app.delete("/shopList/:id",function (req,res) {
    const id=req.params.id
    db.deleteOneById("shopList",id)
        .then(()=>{
            json(res,1,"删除成功")

        }).catch(()=>{
        json(res,-1,"网络异常删除错误")
    })
})
app.delete("/adminList/:id",function (req,res) {
    const id=req.params.id
    db.deleteOneById("adminInfo",id)
        .then(()=>{
            json(res,1,"删除成功")

        }).catch(()=>{
        json(res,-1,"网络异常删除错误")
    })
})



app.delete("/goodsTypeList/:id",function (req,res) {
    const id=req.params.id
    db.deleteOneById("goodsTypeList",id)
        .then(()=>{
            json(res,1,"删除成功")

        }).catch(()=>{
        json(res,-1,"网络异常删除错误")
    })
})


app.post("/shopTypeList",function (req,res) {
    upPic(req, "shopTypePic").then(({ok, params, msg}) => {
        if (ok === 3) {
            db.insertOne("shopTypeList", {
                shopTypeName: params.shopTypeName,
                shopTypePic: params.shopTypePic,
                createTime: Date.now(),
                upTime: Date.now(),
            }).then(data => {
                json(res, 1, "上传成功")
            }).catch(err => {
                json(res)
            })
        } else {
            json(res, -1, msg)
        }
    })
})

app.post("/shopList",function (req,res) {
    upPic(req,"shopPic").then(async ({ok,msg,params})=>{
        if(ok === 3) {
            // 根据类别ID获得类别信息
            const info = await db.findOneById("shopTypeList",params.shopTypeId);
            params.createTime = params.upTime = Date.now();
            params.shopTypeId = info._id;
            params.shopTypeName = info.shopTypeName;

            await db.insertOne("shopList",params)
            // console.log(params)


            // db.insertOne("shopList",{
            //     ...params,
            //     ...{
            //         createTime:Date.now(),
            //         upTime:Date.now(),
            //         shopTypeId:info._id,
            //         shopTypeName:info.shopTypeName
            //     }
            // })

            json(res,1,msg);
        }
        else json(res,-1,msg);
    })
})

app.get("/shopList",async function (req,res) {
    let pageIndex=(req.query.pageIndex || 1)/1  //当前页
    const whereObj={};
    let shopName=req.query.shopName || ""
    if(shopName.length>0){
        whereObj.shopName=new RegExp(shopName)
    }
    let count=await db.count('shopList',whereObj)   //总条数
    let limit=5;  //一页显示
    let pageSum=Math.ceil(count/limit)   //总页数
    if(pageSum<1) pageSum=1
    if(pageIndex>pageSum)pageIndex=pageSum
    if(pageIndex<1) pageIndex=1

    db.find("shopList",{
        sortObj:{
            createTime: -1
        },
        whereObj,
        limit,
        skip:(pageIndex-1)*limit

    }).then(shopList=>{
        setTimeout(()=>{
            res.json({
                ok:1,
                shopList,
                pageIndex,
                pageSum
            })
        },500)
    })
})

app.get("/shopList/:shopTypeId",async function (req,res) {
    const shopTypeId=mongodb.ObjectId(req.params.shopTypeId)
    const shopList= await db.find("shopList",{
        sortObj:{
            createTime:-1
        },
        whereObj:{
            shopTypeId
        }
    })
    res.json({
        ok:1,
        shopList
    })
})

app.post("/goodsTypeList",async function (req,res) {

    const shopInfo=await db.findOneById("shopList",req.body.shopId)
    await db.insertOne("goodsTypeList",{
        goodsTypeName: req.body.goodsTypeName,
        createTime:Date.now(),
        upTime:Date.now(),
        shopId:shopInfo._id,
        shopName:shopInfo.shopName,
        shopTypeId:shopInfo.shopTypeId,
        shopTypeName:shopInfo.shopTypeName
    })
    res.json({
        ok:1
    })
})
app.post("/adminList",async function (req,res) {
    // console.log({passWord:md5(req.body.mima)})
    await db.insertOne("adminInfo",{
        adminName:req.body.zhanghao,
        passWord:md5(req.body.mima+"*^&%**(%$")
    })
    res.json({
        ok:1
    })
})


app.get("/goodsTypeList",async function (req,res) {
    let pageIndex=(req.query.pageIndex || 1)/1  //当前页
    const whereObj={};
    let goodsTypeName=req.query.goodsTypeName || ""
    if(goodsTypeName.length>0){
        whereObj.goodsTypeName=new RegExp(goodsTypeName)
    }
    let count=await db.count('goodsTypeList',whereObj)   //总条数
    let limit=5;  //一页显示
    let pageSum=Math.ceil(count/limit)   //总页数
    if(pageSum<1) pageSum=1
    if(pageIndex>pageSum)pageIndex=pageSum
    if(pageIndex<1) pageIndex=1

    db.find("goodsTypeList",{
        sortObj:{
            createTime: -1
        },
        whereObj,
        limit,
        skip:(pageIndex-1)*limit

    }).then(goodsTypeList=>{
        setTimeout(()=>{
            res.json({
                ok:1,
                goodsTypeList,
                pageIndex,
                pageSum
            })
        },500)
    })
})

//上传图片接口
app.post("/goodsList",function (req,res) {
    upPic(req, "goodsPic").then(({ok, params, msg}) => {
        if (ok === 3) {
            db.insertOne("goodsList", {
                goodsName: params.goodsName,
                goodsPic: params.goodsPic,
                createTime: Date.now(),
                upTime: Date.now(),
                isTrue:params.isTrue
            }).then(data => {
                json(res, 1, "上传成功")
            }).catch(err => {
                json(res)
            })
        } else {
            json(res, -1, msg)
        }
    })
})
app.get("/goodsList",async function (req,res) {
    let pageIndex=(req.query.pageIndex || 1)/1  //当前页
    const whereObj={};
    let goodsName=req.query.goodsName || ""
    if(goodsName.length>0){
        whereObj.goodsName=new RegExp(goodsName)
    }
    let count=await db.count('goodsList',whereObj)   //总条数
    let limit=5;  //一页显示
    let pageSum=Math.ceil(count/limit)   //总页数
    if(pageSum<1) pageSum=1
    if(pageIndex>pageSum)pageIndex=pageSum
    if(pageIndex<1) pageIndex=1

    db.find("goodsList",{
        sortObj:{
            createTime: -1
        },
        whereObj,
        limit,
        skip:(pageIndex-1)*limit

    }).then(goodsList=>{
        setTimeout(()=>{
            res.json({
                ok:1,
                goodsList,
                pageIndex,
                pageSum
            })
        },500)
    })
})
app.delete("/goodsList/:id",function (req,res) {
    const id=req.params.id
    db.deleteOneById("goodsList",id)
        .then(()=>{
            json(res,1,"删除成功")

        }).catch(()=>{
        json(res,-1,"网络异常删除错误")
    })
})

//修改
app.put("/shopList",function (req,res) {
    upPic(req,"shopPic").then(async ({ok,params,msg})=>{
        console.log(ok)
        if(ok===2){// 格式 不正确
            json(res,-1,msg);
        }else{
            console.log(ok,params);
            const info = await db.findOneById("shopTypeList",params.shopTypeId);
            const $set = {
                shopName:params.shopName,
                // shopPic:店铺图片
                shopTypeId:info._id,
                shopTypeName:info.shopTypeName,
                upTime:Date.now()
            }
            // 判断如果上传图片，更新图片
            if(ok === 3){
                $set.shopPic=params.shopPic;
            }
            // 可用
            await db.updateOneById("shopList",params.shopId,{$set});
            res.json({
                ok:1,
                msg:"成功"
            })
        }
    })
})




app.listen(80,()=>{
        console.log('Success')
})